function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

function reverseList(head) {
    if (head == null || head.next == null) return head;
    let pre = null;
    let cur = head, next = head;
    while (cur != null) {
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
};


// 给你单链表的头指针 head 和两个整数 left 和 right ，其中 left <= right 。
// 请你反转从位置 left 到位置 right 的链表节点，返回 反转后的链表 。

const reverseLinkedList = (head) => {
    let pre = null;
    let cur = head;

    while (cur) {
        const next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
}

function reverseBetween(head, left, right) {
    if (head == null || head.next == null) return head;
    const dummy = new ListNode(-1);
    dummy.next = head;
    let pre = dummy;

    for (let i = 0; i < left - 1; i++) {
        pre = pre.next;
    }
    let leftNode = pre.next;

    let rightNode = dummy;
    for (let j = 0; j < right; j++) {
        rightNode = rightNode.next;
    }
    let cur = rightNode.next;

    pre.next = null;
    rightNode.next = null;

    reverseLinkedList(leftNode);
    // reverseList(leftNode);

    pre.next = rightNode;
    leftNode.next = cur;
    return dummy.next;
};